﻿using UnityEngine;
using System.Collections;

public class PhysBoat : MonoBehaviour {

	public Rigidbody inputRigidBody;
	public ConstantForce outputConstantForce;

	public float maxAngVel = 100.0f;

	public bool boatEnable = true;
	public float boatBuoyancy = 2;
	public float boatRadius = 1;
	public float boatDragAir = 1;
	public float boatDragAngAir = 1;
	public float boatDragWater = 6;
	public float boatDragAngWater = 4;
	public float probeBoatY = 0;

	public bool windEnable = true;
	public float wind = 1.0f;
	public float windAng = 0.05f;
	public float windChaos = 2.0f;

	// Use this for initialization
	void Start () {
		inputRigidBody.maxAngularVelocity = maxAngVel;
	}


	void FixedUpdate() {

		float buoyancy = 0;
		float windForceX = 0;
		float windForceZ = 0;

		if (boatBuoyancy != 0) {

			float y = 0;
			if (transform.position.y > boatRadius)
				y = 0;
			else if (transform.position.y < -boatRadius)
				y = 1.0f;
			else
				y = (boatRadius - transform.position.y) / 2;
			probeBoatY = y;

			buoyancy = 9.81f * 1 * y*boatBuoyancy*inputRigidBody.mass;

			inputRigidBody.drag = boatDragAir * (boatDragWater-boatDragAir)*y;
			inputRigidBody.angularDrag = boatDragAngAir * (boatDragAngWater-boatDragAngAir)*y;

		}

		if (wind != 0) {
			float t = (Time.realtimeSinceStartup);
			t *= windChaos;
			t += transform.position.x + transform.position.z;
			t *= 2*Mathf.PI;
			float wind1 = Mathf.Cos (t / 7);
			wind1 +=      Mathf.Cos (t / 27);
			float wind2 = Mathf.Cos (t / 11);
			wind2 +=      Mathf.Cos (t / 4 );
			float wind3 = Mathf.Cos (t / 21);
			wind3 +=      Mathf.Cos (t / 31);

			
			outputConstantForce.torque = new Vector3 (windAng * inputRigidBody.mass * wind1,
			                                          windAng * inputRigidBody.mass * wind2,
			                                          windAng * inputRigidBody.mass * wind3);

			windForceX = wind * (wind1 + wind2/2) * inputRigidBody.mass;
			windForceZ = wind * (wind3 + wind2/2) * inputRigidBody.mass;

		}

		float wind4 =           (Time.realtimeSinceStartup * 6.28f / 23 * windChaos);
		outputConstantForce.force = Quaternion.Euler(0, wind4, 0) * new Vector3 (windForceX, buoyancy, windForceZ);


	}
}
